package pers.qianyu.diytomcat.servlets;

import pers.qianyu.diytomcat.catalina.*;
import pers.qianyu.diytomcat.constants.*;
import pers.qianyu.diytomcat.http.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/**
 * 处理 Servlet 的 Servlet
 *
 * @author mizzle rain
 * @date 2021-01-08 15:25
 */
public class InvokerServlet extends HttpServlet {
    private static final InvokerServlet INSTANCE = new InvokerServlet();

    public synchronized static InvokerServlet getInstance() {
        return INSTANCE;
    }

    private InvokerServlet() {
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        try {
            Request request = (Request) req;
            Response response = (Response) res;

            String uri = request.getUri();
            Context context = request.getContext();
            String servletClassName = context.getServletClassName(uri);
            Class<?> servletClass = context.getWebappClassLoader().loadClass(servletClassName);
            HttpServlet servlet = context.getServlet(servletClass);
            servlet.service(request, response);
            if (Objects.isNull(response.getRedirectPath())) {
                response.setStatus(HttpCode.CODE_200);
            } else {
                response.setStatus(HttpCode.CODE_302);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
